package com.prs.crm.conversion;

import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.Map;

import javax.servlet.ServletContext;

import ognl.DefaultTypeConverter;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.courser.hibernate.XJEntity;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.prs.crm.service.QueryService;

public class EntityConverter  extends DefaultTypeConverter{
	 private static final Logger log = Logger.getLogger(EntityConverter.class);
	 
		private QueryService service;
		public QueryService getService() {
			if (service==null)
			{
				ServletContext sc = ServletActionContext.getServletContext();
				 WebApplicationContext wac = WebApplicationContextUtils
		          .getWebApplicationContext(sc);
			      return (QueryService) wac.getBean("queryService");
			}
			return service;
		}
		
		
		@SuppressWarnings("unchecked")
		@Override
		public Object convertValue(Map context, Object o, Class toType)
		{
			Serializable id=null;
			if (toType==String.class || toType==Integer.class)
			{
				if (o instanceof XJEntity && o!=null)
				{
					try
					{
						return PropertyUtils.getProperty(o, "id");
					}
					catch (Exception e)
					{
						log.error(e);
						return null;
					}
				}
			}
			else if (o instanceof String || o instanceof Integer)
				id = (String)o;
			else if (o instanceof String[] || o instanceof Integer[])
			{
				Serializable[] ary = (Serializable[])o;
				if (ary.length>0)
					id = ary[0];
			}
			if (id!=null && id.toString().trim().length()>0)
			{
				log.debug("auto conver "+toType.getName());
				try
				{
					Method method= toType.getMethod("getId");
					if (method!=null && method.getReturnType()!=null)
					{
						if (method.getReturnType().equals(Integer.class))
							id = Integer.valueOf(id.toString());
						else if (method.getReturnType().equals(int.class))
							id = Integer.valueOf(id.toString()).intValue();
					}
				}
				catch (Exception e)
				{
					log.error(e);
				}
		
				return this.getService().load(toType, id);
			}
			else
			{
				return null;
			}
		}
}